<?php
namespace app\lib\coze;

use think\Db;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Api 
{

    public function getJwt(){
        $header = [
            'alg'=>'RS256',
            'typ'=>'JWT',
            'kid'=>'0WuOsNd6h5373jUfzpMjezg654tMe07Cbs9gU6DTKqo'
        ];
        $payload = [
            "iss"=>"1107185658032",   // OAuth 应用的 ID
            "aud"=>"api.coze.cn",   //扣子 API 的Endpoint
            "iat"=>time(),       // JWT开始生效的时间，秒级时间戳
            "exp"=>time()+3600,       // JWT过期时间，秒级时间戳
            "jti"=>uuidCreate() // 随机字符串，防止重放攻击
        ];
        $privateKey = file_get_contents('./coze_jwt/private_key.pem');
        
        $jwt = JWT::encode($payload, $privateKey, 'RS256', $header['kid'], $header);

        // $header = base64_encode(json_encode($header,JSON_UNESCAPED_UNICODE));
        // $payload = base64_encode(json_encode($payload,JSON_UNESCAPED_UNICODE));
        // dump($header);
        // dump($payload);die;
        
        return $jwt;
    }

    public function getAccountToken(){
        $jwt = $this->getJwt();
        if (empty($jwt)) {
            return false;
        }
        $api_url = 'https://api.coze.cn/api/permission/oauth2/token';
        $header = [
            'Content-Type:application/json',
            'Authorization:Bearer '.$jwt
        ];
        $result = httpRequest($api_url,json_encode([
            'duration_seconds'=>86399,
            'grant_type'=>'urn:ietf:params:oauth:grant-type:jwt-bearer'
        ]),'POST',$header);
        $result = json_decode($result,true);

        return $result['access_token'];
    }

   
}
